<template>
  <div>
    <el-card>
      <el-form :model="form" size="mini" label-position="top" ref="form">
        <el-row :gutter="10">
          <el-col :lg="4" :md="6">
            <el-form-item label="机构">
              <!-- <el-popover placement="bottom" width="200" trigger="click" v-model="popoverShow">
                <el-tree :data="treedata" default-expand-all :props="defaultProps" @node-click="handleNodeClick">
                </el-tree>
                <el-input slot="reference" v-model="form.branchName" placeholder="请选择机构"></el-input>
              </el-popover> -->
              <select-tree :branch="form.branchName" @getBranchName="getBranch"></select-tree>
            </el-form-item>
          </el-col>
          <el-col :lg="4" :md="6">
            <el-form-item label="人力需求编号" prop="FTEID">
              <el-input v-model="form.FTEID" placeholder="请输入人力需求编号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="4" :md="6">
            <el-form-item label="人力需求名称" prop="FTENAME">
              <el-input v-model="form.FTENAME" placeholder="请输入人力需求名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg='6' :md='6' :offset="6" class="searchBtnMarginTop">
            <el-button type="primary" icon="el-icon-search" @click="FTEQuery" size='mini'>查询
            </el-button>
          
            <el-button type="warning" size="mini" icon="el-icon-refresh" @click="resetForm('form')">重置</el-button>
          </el-col>
        </el-row>
        <el-row >
          <el-col :lg="6"  :md="12">
            <el-button type="primary" size="mini" icon="el-icon-plus" @click="addFTE">新增人力需求</el-button>
            <el-button type="success" size="mini" icon="el-icon-download" @click="downloadTemplate">模板下载</el-button>
          </el-col>
          
        </el-row>
      </el-form>
      <div>
        <el-table :data="tableData" style="margin-top:20px;">
          <el-table-column prop="FTEID" label="人力需求编号"></el-table-column>
          <el-table-column prop="FTENAME" label="人力需求名称"></el-table-column>
          <el-table-column prop="BRANCHNAME" label="机构名称">
            <template slot-scope="scope">
              <span>
                {{BRANCHNAME}}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="SKILLFLG" label="技能"></el-table-column>
          <el-table-column prop="NOTES" label="说明"></el-table-column>
          <el-table-column prop="FTEDTL" label="明细" align="center">
            <template slot-scope="scope">
              <div>
                <el-button type="text" size="small" @click="openDetail(scope.row)"><i class="el-icon-search"></i>查看明细
                </el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="160" align="center">
            <template slot-scope="scope">
              <el-button @click="update(scope.row)" type="warning" size="mini">修改</el-button>
              <el-button type="danger" size="mini" @click="delFTE(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- <el-row>
          <el-col>
          <el-pagination style="text-align: right; margin-top:20px;" 
            :page-sizes="[10, 20, 50, 100]" 
            :page-size="pageSize" 
            @size-change="handleInSizeChange" 
            @current-change="handleInCurrentChange" 
            :current-page="currpage" 
            background layout="sizes, total, prev, pager, next, jumper" 
            :total="tableTotal">
          </el-pagination>
        </el-col>
        </el-row> -->
      </div>
      <el-dialog title="查看明细" :visible.sync="detailVisible" :close-on-click-modal="false" width="80%"
        @open="openDetailDialog">
        <el-card>
          <div id="detail" style="width: 100%;height: 400px;"></div>
        </el-card>
      </el-dialog>
      <component :is="dialogList.editDialog" :option="editOptions" @ListenFTE="FTEQuery"></component>
      <component :is="dialogList.updateDialog" :option="updateOptions" @ListenFTE="FTEQuery"></component>

    </el-card>
  </div>
</template>
<script>
  import editDialog from './dialog/editDialog'
  import updateDialog from './dialog/updateDialog'
  import request from "@/common/utils/requestWFM";
  import Query from '@/message/wfm/intelligenceSchedule/FTEMaintain/FTEQuery'
  import detialQuery from '@/message/wfm/intelligenceSchedule/FTEMaintain/FTEDetailQuery'
  import Del from '@/message/wfm/intelligenceSchedule/FTEMaintain/FTEDel'
  import getGlobalParams from "@/common/utils/getGlobalParams";
  import echarts from 'echarts'
  import branchQuery from '@/message/wfm/baseData/branchManage/branchQuery'
  import download from '@/message/wfm/public/templateDownload'
  import numQuery from '@/message/wfm/scheduleDataManage/branchData/branchDataQuery';
  import selectTree from "@/components/selectTree5/";
  import dataQuery from '@/message/wfm/baseData/dictionaryManage/dictionaryQuery';

  export default {
    components: {
      selectTree
    },
    data() {
      return {
        maxNum: 0,
        popoverShow: false,
        defaultProps: {
          children: 'children',
          label: 'BRANCHNAME'
        },
        fileUrl: getGlobalParams.get("FileDownloadAddress"),
        detailVisible: false, //查询明细的dialog
        xDetailData: [],
        xData: [],
        BRANCHNO: '',
        BRANCHNAME: '',
        tableTotal: 1,
        currpage: 1,
        pageSize: getGlobalParams.get("PageSize"),
        form: { //表单数据
          FTENAME: '',
          FTEID: '',
          branchNO: this.$store.getters.BranchNum,
          branchName: this.$store.getters.BranchName,
        },
        queryDetailData: [],
        resData: "",
        treedata: [],
        actId: '',
        editOptions: {
          isShow: false,
          title: '',
          treedata: []
        },
        updateOptions: {
          FTE: [],
          isShow: false,
          row: {},
          branchName: '',
          BRANCHID: '',
          dateOption: []
        },
        dialogList: {
          editDialog,
          updateDialog
        },
        tableData: [],
        SKILLFLGS: [],  //技能字段
      }
    },
    mounted() {
      this.FTEQuery();
      this.dataDictionaryQuery();
    },
    methods: {
      getBranch(data){
        this.form.branchNO = data.BRANCHNO
        this.form.branchName= data.BRANCHNAME
      },
      // 下载模板
      async downloadTemplate() {
        let resBody = new download()
        resBody.data.TempType = 'FTE'
        let response = await request(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          let res = response.BODY
          let name = res.FileName
          let url = res.FilePath
          // console.log(this.fileUrl + url + '/' + name)
          this.downloadFile(this.fileUrl + url + '/' + name)
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          })
        }
      },
      // 查看FTE明细
      async queryDetail(id,type) {
        let resBody = new detialQuery()
        resBody.data.FTEID = id
        let response = await request(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          this.queryDetailData = response.BODY.FTEDTL
          if(type=='query'){
          this.xDetailData = []
          this.detailData = []
          let arr = []
          this.queryDetailData.forEach((item, index) => {
            // item.FDATE = this.timeFormat2Date(item.FDATE)
            let str = item.FDATE + ' ' + item.FTIME
            this.xDetailData.push(str)
            arr.push(item.MANCOUNT)
          });
          let arr1 = []
          arr = arr.join(',').split(',')
          arr.forEach((item, index) => {
            item = item.split(',')
            item.unshift(index)
            arr1.push(item)
          });
          this.detailData = arr1
          // console.log(this.xDetailData)
          this.detailVisible = true
          }else{
            this.updateOptions.FTE = response.BODY.FTEDTL
            const obj = {}
            const newObjArr =  this.updateOptions.FTE.reduce((prev, curr)=>{
              obj[curr.FDATE] ? true : obj[curr.FDATE] = true && prev.push({text:curr.FDATE,value:curr.FDATE});
              return prev
            }, [])
            this.updateOptions.dateOption = newObjArr
            this.updateOptions.isShow = true
            this.updateOptions.row.BRANCHNAME = this.form.BRANCHNAME
            this.updateOptions.row.FTENAME = type.FTENAME
            this.updateOptions.row.FTEID = type.FTEID
            this.updateOptions.row.NOTES = type.NOTES
            this.updateOptions.row.BRANCHNO = this.form.BRANCHNO
            this.updateOptions.row.SKILLFLG = type.SKILLFLG
          }
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          })
        }
      },
      // 查看明细的dialog打开时
      openDetailDialog() {
        this.$nextTick(async () => {
            let resBody = new numQuery()
            resBody.data.BRANCHNO = this.form.BRANCHNO
            let response = await request(resBody);
            if (response.SYS_HEAD.ReturnCode == "000000") {
              this.maxNum = response.BODY.RSPSTRUCT[0].AGENTNUM
            } else {
              this.$message({
                type: "error",
                message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD
                  .ReturnMessage
              })
            }
          this.drawDetail()
        })
      },
      // 打开查看明细的dialog
      async openDetail(row) {
        this.queryDetail(row.FTEID,'query')
      },
      drawDetail() {
        this.myChart = echarts.init(document.getElementById('detail'))
        this.myChart.setOption({
          title: {
            text: '人力需求折线图',
            left: 'center',
            fontStyle: 'normal',
            fontWeight: 'bold',
          },
          tooltip: {
            // trigger: 'none',
            trigger: 'axis',
            formatter: (params) => {
              return '时间: ' + params[0].axisValueLabel + '<br>人力: ' + params[0].data[1];
            }
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: this.xDetailData,
            axisLine: {
              onZero: false
            }
          },
          yAxis: {
            min: 0,
            max: this.maxNum,
            type: 'value',
            axisLabel: {
              formatter: function (value, index) {
                return parseInt(value)
              }
            },
            axisLine: {
              onZero: false
            }
          },
          dataZoom: [{
              type: 'slider',
              xAxisIndex: 0,
              filterMode: 'empty'
            },
            {
              type: 'inside',
              xAxisIndex: 0,
              filterMode: 'empty'
            },
          ],
          series: [{
            id: 'a',
            type: 'line',
            smooth: true,
            data: this.detailData,
            hoverAnimation: false,
            itemStyle: {
              normal: {
                borderColor: '#63A07B', // 边框颜色
                color: '#fafafa', // 折线上标记点的颜色 和 图例的颜色
                lineStyle: {
                  width: 2, //  折线图的粗细
                  color: '#538767' // 折线的颜色
                }
              }
            },
          }, ],
        })
      },
      update(row) {
        // console.log(row)
        // this.updateOptions.isShow = true
        // this.updateOptions.row = row
        // this.updateOptions.row.branchName = this.BRANCHNAME
        // this.updateOptions.row.BRANCHNO = this.BRANCHNO
        this.updateOptions.SKILLFLGS = this.SKILLFLGS;
        this.queryDetail(row.FTEID,row)
      },
      //前端分页
      handleInCurrentChange(val) {
        this.currpage = val;
        // console.log(`当前页: ${val}`);
      },
      handleInSizeChange(val) {
        this.pageSize = val;
      },
      resetForm(formName) { //重置查询表单
        this.$refs[formName].resetFields();
        // this.checkedIds = [];
      },
      addFTE() {
        this.editOptions.isShow = true;
        this.editOptions.treedata = this.treedata;
        this.editOptions.SKILLFLGS = this.SKILLFLGS;
      },
      // 活动查询
      async FTEQuery() {
        let resBody = new Query()
        resBody.data.BRANCHNO = this.form.branchNO
        resBody.data.FTEID = this.form.FTEID
        resBody.data.FTENAME = this.form.FTENAME
        // resBody.data.CurrPage = this.currpage; 
        // resBody.data.PageRowNum = this.pageSize; 
        let response = await request(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          this.tableData = response.BODY.RSPSTRUCT
          // console.log(this.tableData)
          // this.tableTotal = response.BODY.TotalRowNum;
          this.BRANCHNAME = response.BODY.BRANCHNAME;
          this.BRANCHNO = response.BODY.BRANCHNO
          this.form.BRANCHNO = response.BODY.BRANCHNO
          this.form.BRANCHNAME = response.BODY.BRANCHNAME
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          })
        }
      },
      // 删除FTE
      delFTE(row) {
        this.$confirm('此操作将删除该人力需求, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let resBody = new Del()
          resBody.data.FTEID = row.FTEID
          let response = await request(resBody);
          if (response.SYS_HEAD.ReturnCode == "000000") {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.FTEQuery()
          } else {
            this.$message({
              type: "error",
              message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
            })
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        })
      },
      // 技能参数查询
      async dataDictionaryQuery() {
        let resBody = new dataQuery();
        resBody.data.FIELDCODE = 'AGENTSKILL';
        resBody.data.FIELDNAME = '';
        resBody.data.CurrPage = 1;
        resBody.data.PageRowNum = 100;
        let response = await request(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          this.SKILLFLGS = response.BODY.FIEDATA;
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          })
        }
      },
    },
  }

</script>

<style lang="scss" scoped>
</style>
